package com.mallotec.android.timenote.ui.adapter.base;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder;

import org.jetbrains.annotations.NotNull;

public abstract class BaseDataBindingAdapter<
        Item,
        ViewBinding extends ViewDataBinding,
        ViewModel extends androidx.lifecycle.ViewModel,
        DataBindingHolder extends BaseDataBindingHolder2<ViewBinding, ViewModel>
        > extends BaseQuickAdapter<Item, DataBindingHolder> {

    private final ViewModel viewModel;

    public BaseDataBindingAdapter(int itemLayoutId, ViewModel viewModel) {
        super(itemLayoutId);
        this.viewModel = viewModel;
    }
		
    /**
     * 当 ViewHolder 创建完毕以后，会执行此回掉
     * 可以在这里做任何你想做的事情
     */
    @Override
    protected void onItemViewHolderCreated(@NotNull DataBindingHolder viewHolder, int viewType) {
        // 绑定 view
        // DataBindingUtil.bind(viewHolder.itemView);
        viewHolder.bindViewModel(viewModel);
    }

    @Override
    protected void convert(@NotNull DataBindingHolder helper, @NotNull Item item) {
        if (item == null) {
            return;
        }

        // 获取 Binding
        ViewBinding binding = helper.getDataBinding();
        if (binding != null) {
            // 设置数据
            bind(binding, item);
            binding.executePendingBindings();
        }
    }

    protected abstract void bind(ViewBinding binding, Item item);
}